package com.sydsen.imager.processor;

import com.sydsen.imager.elements.Element;
import com.sydsen.imager.elements.Text;
import com.sydsen.imager.painter.IPainter;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;

/**
 * @Auther: syh
 * @Date: 2021/11/1
 * @Description:
 */
public class ProcessorFactory {

    static final Map<Class<? extends Element>, IProcessor<? extends Element>> painterMap =
            new HashMap<>();

    public static <T extends Element<T>> IProcessor<T> getProcessor(Element element) {
        IProcessor<T>  processor = (IProcessor<T>)painterMap.get(element.getClass());
        if (processor == null) {
            processor = (IProcessor<T>) PROCESSOR.of(element.getClass()).get();
            painterMap.put(element.getClass(), processor);
        }

        return processor;
    }


    private enum PROCESSOR {
        TEXT(Text.class, TextProcessor::new);

        private Class<? extends Element> clazz;
        private Supplier<IProcessor<? extends Element>> supplier;

        PROCESSOR(Class<? extends Element> clazz, Supplier<IProcessor<? extends Element>> supplier) {
            this.clazz = clazz;
            this.supplier = supplier;
        }

        public static Supplier<IProcessor<? extends Element>> of(Class<? extends Element> clazz) {
            for (PROCESSOR value : PROCESSOR.values()) {
                if (value.clazz.getName().equals(clazz.getName())) {
                    return value.supplier;
                }
            }
            return DefaultProcessor::new;
        }
    }
}
